package com.tencent.service;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import com.tencent.common.Configure;

/**
 * 获取微信用户信息
 * @author 唐乾红
 * @修改日期 2016-08-02 10:00:00
 */
public class WxJsapiTicketService {
	private static final Log logger = LogFactory.getLog(WxJsapiTicketService.class);

	/**
	 *jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下，jsapi_ticket的有效期为7200秒，通过access_token来获取。
	 *由于获取jsapi_ticket的api调用次数非常有限，频繁刷新jsapi_ticket会导致api调用受限，影响自身业务，开发者必须在自己的服务全局缓存jsapi_ticket。
	 */
	public static final Map<String, String> jsapiTicketMap = new HashMap<String, String>();
	public static final Map<String, Long> ticketCreateTime = new HashMap<String, Long>();
	/**
	 * 创建获取code链接
	 * @param appid 公众号appid
	 * @param url 回调函数url
	 * @param state 回调函数传回参数
	 * @param scope 链接授权作用域
	 */
	public synchronized static String getJsapiTicket(String appid, String accessToken) {
		if (isTicketTimeout(appid)) {
			refreshJsapiTicket(appid, accessToken);
		}
		return jsapiTicketMap.get(appid);
	}

	public static boolean isTicketTimeout(String appid) {
		long currentTime = System.currentTimeMillis();
		long lastGetTime = ticketCreateTime.get(appid) == null ? 0 : ticketCreateTime.get(appid) ;
		return (currentTime - lastGetTime) >= (Configure.TICKET_TIMEOUT * 1000);
	}

	public synchronized static void refreshJsapiTicket(String appid) {
		ticketCreateTime.put(appid, Long.valueOf(0));
	}
	
	/**
	 * 刷新
	 * @param appid
	 * @param accessToken
	 * @return
	 */
	private synchronized static void refreshJsapiTicket(String appid, String accessToken) {
		try {
			String url = Configure.TICKET_API.replace("ACCESS_TOKEN", accessToken);
			HttpGet request = new HttpGet(url);
			HttpResponse response = HttpClients.createDefault().execute(request);
			if (response.getStatusLine().getStatusCode() == 200) {
				String result = EntityUtils.toString(response.getEntity());
				JSONObject jsonObject = new JSONObject(result);
				jsapiTicketMap.put(appid, (String) jsonObject.get("ticket"));
				ticketCreateTime.put(appid, System.currentTimeMillis());
			}
		} catch (Exception e) {
			logger.error("获取jsapi_ticket失败", e);
		}
	}


	
}
